//
//  AddProductViewController.m
//
//
//  Created by Abner on 16/4/28.
//
//
#import "AddProductViewController.h"
#import "ProductCodeCell.h"
#import "ProductArrowCell.h"
#import "ProductTextCell.h"
#import "ProductSwitchCell.h"
#import "ProduntImageCell.h"
#import "ProductIntroductViewController.h" //商品简介（只有文字）

#import "AJPhotoPickerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AJPhotoBrowserViewController.h"

#import "ZBarScanVC.h" //条码扫描界面
#import "ProductImgTextIntroductViewController.h" //图文详情描述界面
#import "StartSellTimeViewController.h" //开售时间

#import "CropImgViewController.h" //裁剪图片
#import "classifyViewController.h"//分类

#import "MBProgressHUD.h"
#import "MBProgressHUD+LCHud.h"

//2016-09-22
#import "ProductSpecCell.h"
#import "ProductSpecDeleteCell.h"
#import "ProductPropDeleteCell.h"
#import "AddProductFooterView.h"
#import "AddProduct.h"
#import "SelectImageViewController.h"

#define NOTIFIC_NAME @"notific_name_sendImages"
#define KSpecArrPlaceholder @"LCSpec"
#define KPropArrPlaceholder @"LCProp"

@interface AddProductViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,AJPhotoPickerProtocol,UIImagePickerControllerDelegate,UINavigationControllerDelegate,backNameAndIdDelegate,SendNumDelegate,UIAlertViewDelegate,UIActionSheetDelegate,ProductCodeCellDelegate,ProductSpecDeleteCellDelegate,ProductPropDeleteCellDelegate>
{
    AddProduct *aLcProducct;//定义一个全局的AddProduct来上传发布
    BOOL _isReload; //添加成功，继续添加
    BOOL _isFailed; //断网或者什么原因提交失败
    NSInteger _localImgCount; //本地图片数量
    
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)AJPhotoPickerViewController *picker; //选择照片
@property (strong, nonatomic) NSMutableArray *photos; //包含finalImgs和网络图片
@property (strong, nonatomic) NSMutableArray *finalImgs; // 最终的图片【本地图片】（base64）
@property (strong, nonatomic) NSMutableArray *sendedPhotos; //最终的要上传的（包含网络请求的以及本地的）

@property (strong, nonatomic) UIButton *leftBotBt; // 在此处声明是为了全局调用，控制其是否可点
@property (strong, nonatomic) UIButton *rightBotBt; //

@property(nonatomic,strong)UIView *mengBanView; //蒙版view

/** 多规格数组 */
@property(nonatomic,strong)NSMutableArray *productSpecArrs;
/** 多属性数组 */
@property(nonatomic,strong)NSMutableArray *productPropArrs;
@end

@implementation AddProductViewController

#pragma mark --- 图片数组懒加载
-(NSMutableArray *)sendedPhotos
{
    if (_sendedPhotos == nil) {
        _sendedPhotos = [NSMutableArray array];
    }
    return _sendedPhotos;
}

-(NSMutableArray *)finalImgs
{
    if (_finalImgs == nil) {
        _finalImgs = [NSMutableArray array];
    }
    return _finalImgs;
}
-(NSMutableArray *)productSpecArrs
{
    if (_productSpecArrs == nil) {
        _productSpecArrs = [NSMutableArray array];
    }
    return _productSpecArrs;
}
-(NSMutableArray *)productPropArrs
{
    if (_productPropArrs == nil) {
        _productPropArrs = [NSMutableArray array];
    }
    return _productPropArrs;
}

-(void)toHideKeyboard
{
    [self.view endEditing:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
  
    /*
     备用2016-06-01，如果左上角的返回按钮可以点击，则用下面的方法（上面添加tableView和BottomView）
     */
    //    self.mengBanView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight)];
    //    self.mengBanView.backgroundColor = [UIColor clearColor];
    //    [self.view addSubview:self.mengBanView];
    
    NSString *titleStr;
    if (self.addVCStyle == LCProductStyleAdd) {
        titleStr = @"添加商品";
    }else if (self.addVCStyle == LCProductStyleEdit){
        titleStr = @"编辑商品";
    }
    [self initNav:titleStr doBack:YES];
    //给导航栏添加点击事件，隐藏键盘
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toHideKeyboard)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.navBar addGestureRecognizer:tapGestureRecognizer];
    self.view.backgroundColor = SetColorRGBValue(0xF9F9F9, 1.0);
    
    aLcProducct = [[AddProduct alloc]init];
    _photos = [NSMutableArray array];
    _isReload = NO;
    _isFailed = NO;
    [self.productSpecArrs addObject:KSpecArrPlaceholder]; //规格默认至少一个，所以先填充一个标示
    
    [self creatUI];
    [self creatBottomView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardshow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardhide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 注册通知(上传图片)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(overedSendImg:) name:NOTIFIC_NAME object:nil];
    
    if (self.addVCStyle == LCProductStyleEdit) {
        [self getProductEditData];
    }
}
#pragma mark --- 根据userproductid获取商品信息
-(void)getProductEditData
{
    [MBProgressHUD showLCHud:self.view];
    if (kNetworkNotReachability) { // 没有网
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share] showWithMessLC:@"网络不给力,请检查网络"];
        return;
    }else{
        
         NSString *editUrl = [NSString stringWithFormat:GetProductEditDataUrl,self.userproductid,[AppData share].username,@"0"];
        [NTNetUtil sendRequestWithUrl:editUrl requestName:@"getEditData" method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *resultDict = (NSDictionary *)networkRequest.responseData;
            LCLog(@"111根据userproductid获取商品信息--%@\n-%@---\n%@",resultDict,editUrl,aLcProducct);
            if (error) {
                [MBProgressHUD hideLCHud:self.view];
                [[MessShowView share]showWithMessLC:@"没有该商品信息" login:NO];
                //处理扫码没有结果的情况，但是条码框任然显示扫码的结果
                aLcProducct = [AddProduct new];
                self.photos = [NSMutableArray array];
                self.finalImgs = [NSMutableArray array];
                self.sendedPhotos = [NSMutableArray array];
                [self.productSpecArrs removeAllObjects];
                [self.productSpecArrs addObject:KSpecArrPlaceholder];
                [self.productPropArrs removeAllObjects];
                _isReload = YES;
                [self.tableView reloadData];
                [UIView animateWithDuration:0.1 animations:^{
                    [self.tableView setContentOffset:CGPointMake(0, 0)];
                } completion:^(BOOL finished) {
                    
                }];
                
                return ;
                
            }else{
                NSDictionary *dic = (NSDictionary *)networkRequest.responseData;
                aLcProducct = [AddProduct mj_objectWithKeyValues:dic];
                if ([aLcProducct.m isEqualToString:@"success"]) {
                    
                    [MBProgressHUD hideLCHud:self.view];
                    
                    //获取数据成功，先清除原有多规格多属性的数组，如果多规格数组为0，要默认添加一个KSpecArrPlaceholder
                    [self.productSpecArrs removeAllObjects];
                    [self.productPropArrs removeAllObjects];
                    if (aLcProducct.productspec.count > 0) {
                        [self.productSpecArrs addObjectsFromArray:aLcProducct.productspec];
                    }
                    if (self.productSpecArrs.count == 0) {
                        [self.productSpecArrs addObject:KSpecArrPlaceholder];
                    }
                    
                    if (aLcProducct.productprop.count > 0) {
                        [self.productPropArrs addObjectsFromArray:aLcProducct.productprop];
                    }
                    
                    if (aLcProducct.imagelist.count > 0) { //先判断是否有网络请求图片
                        [self.photos addObjectsFromArray:aLcProducct.imagelist];
                    }
                    
                    [self.tableView reloadData];
                }else{
                    
                    [MBProgressHUD hideLCHud:self.view];
                    [[MessShowView share]showWithMessLC:aLcProducct.m login:NO];
                    //处理扫码没有结果的情况，但是条码框任然显示扫码的结果
                    aLcProducct = [AddProduct new];
                    self.photos = [NSMutableArray array];
                    self.finalImgs = [NSMutableArray array];
                    self.sendedPhotos = [NSMutableArray array];
                    [self.productSpecArrs removeAllObjects];
                    [self.productSpecArrs addObject:KSpecArrPlaceholder];
                    [self.productPropArrs removeAllObjects];
                    _isReload = YES;
                    [self.tableView reloadData];
                    [UIView animateWithDuration:0.1 animations:^{
                        [self.tableView setContentOffset:CGPointMake(0, 0)];
                    } completion:^(BOOL finished) {
                        
                    }];
                    
                }
                
            }
            
        }];
        
    }

}
#pragma mark 当键盘出现或改变时调用
-(void)keyBoardshow:(NSNotification *)notification{
    NSDictionary *info=[notification userInfo];
    NSValue *avalue=[info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect=[self.view convertRect:[avalue CGRectValue] fromView:nil];
    double keyboardHeight=keyboardRect.size.height;//键盘的高度
    [UIView animateWithDuration:0.2 animations:^{
        self.tableView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-keyboardHeight-64);
    }];
    
}

-(void)keyBoardhide:(NSNotification *)notification{
    [UIView animateWithDuration:0.2 animations:^{
        self.tableView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-50-64);
    }];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NOTIFIC_NAME object:nil];
    
}

#pragma mark --- 创建TableView
-(void)creatUI
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-114) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    self.tableView = tableView;
    //去掉所有分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //去掉多余的分割线
    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    self.tableView.backgroundColor = SetColorRGBValue(0xF9F9F9, 1.0);
    [self.view addSubview:self.tableView];
    
}
#pragma mark --- 创建底部两个按钮
-(void)creatBottomView
{
    UIView *bottomV = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-50, ScreenWidth, 50)];
    [self.view addSubview:bottomV];
    bottomV.backgroundColor = [UIColor whiteColor];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line.backgroundColor = SetColorRGBValue(0xe0e0e0, 1.0);
    line.alpha = 0.5;
    [bottomV addSubview:line];
    
    
    if (self.addVCStyle == LCProductStyleAdd) {
        CGFloat bottomBTWidth = (ScreenWidth-30)/2;
        UIButton *leftBotBt = [UIButton buttonWithType:UIButtonTypeCustom];
        leftBotBt.frame = CGRectMake(10, 5, bottomBTWidth, 40);
        leftBotBt.backgroundColor = SetColorRGBValue(0xff6600, 1.0);
        [leftBotBt setTitle:@"上架出售" forState:UIControlStateNormal];
        [leftBotBt setTitleColor:SetColorRGBValue(0xffffff, 1.0) forState:UIControlStateNormal];
        [leftBotBt setTitleColor:SetColorRGBValue(0xffffff, 1.0) forState:UIControlStateHighlighted];
        leftBotBt.titleLabel.font = FontSet(16);
        leftBotBt.layer.masksToBounds = YES;
        leftBotBt.layer.cornerRadius = 3;
        self.leftBotBt = leftBotBt;
        [bottomV addSubview:self.leftBotBt];
        
        UIButton *rightBotBt = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBotBt.frame = CGRectMake(leftBotBt.right+10, 5, bottomBTWidth, 40);
        [rightBotBt setTitle:@"加入仓库" forState:UIControlStateNormal];
        [rightBotBt setTitleColor:SetColorRGBValue(0xff6600, 1.0) forState:UIControlStateNormal];
        [rightBotBt setTitleColor:SetColorRGBValue(0xff6600, 1.0) forState:UIControlStateHighlighted];
        rightBotBt.titleLabel.font = FontSet(16);
        rightBotBt.layer.masksToBounds = YES;
        rightBotBt.layer.cornerRadius = 3;
        rightBotBt.layer.borderWidth = 1;
        rightBotBt.layer.borderColor = SetColorRGBValue(0xff6600, 1.0).CGColor;
        self.rightBotBt = rightBotBt;
        [bottomV addSubview:self.rightBotBt];
        
        
        [leftBotBt addTarget:self action:@selector(leftBotBtClicked) forControlEvents:UIControlEventTouchUpInside];
        [rightBotBt addTarget:self action:@selector(rightBotBtClicked) forControlEvents:UIControlEventTouchUpInside];

    }else if (self.addVCStyle == LCProductStyleEdit){
        CGFloat saveBtW = ScreenWidth-80*2;
        UIButton *saveBt = [UIButton buttonWithType:UIButtonTypeCustom];
        saveBt.frame = CGRectMake(80, 5, saveBtW, 40);
        saveBt.backgroundColor = SetColorRGBValue(0xff6600, 1.0);
        [saveBt setTitle:@"保存" forState:UIControlStateNormal];
        [saveBt setTitleColor:SetColorRGBValue(0xffffff, 1.0) forState:UIControlStateNormal];
        [saveBt setTitleColor:SetColorRGBValue(0xffffff, 1.0) forState:UIControlStateHighlighted];
        saveBt.titleLabel.font = FontSet(16);
        saveBt.layer.masksToBounds = YES;
        saveBt.layer.cornerRadius = 3;
        [bottomV addSubview:saveBt];
        [saveBt addTarget:self action:@selector(editSaveBtClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
}
#pragma mark --- "上架出售"点击事件
-(void)leftBotBtClicked
{
    aLcProducct.actiontype = @"0";
    [self addOrFangru:@"0"];
}

#pragma mark --- "加入仓库"点击事件
-(void)rightBotBtClicked
{
    aLcProducct.actiontype = @"1";
    [self addOrFangru:@"1"];
}
#pragma mark --- 编辑商品界面"保存"点击事件
-(void)editSaveBtClicked
{
    aLcProducct.actiontype = @"2";
    [self addOrFangru:@"2"];
}
#pragma mark -- 输入信息不完整的提示（抽出来的方法）
-(void)showAlertMessage:(NSString *)message
{
    [MBProgressHUD hideLCHud:self.view];
    [[MessShowView share]showWithMessLC:message login:NO];
    return;
}
#pragma mark -- 输入信息不完整的提示（抽出来的方法.没有return）
-(void)showAlertMessage1:(NSString *)message
{
    [MBProgressHUD hideLCHud:self.view];
    [[MessShowView share]showWithMessLC:message login:NO];
}
#pragma mark --- 发布添加或加入仓库网络请求
-(void)addOrFangru:(NSString *)actiontype
{
    NSLog(@"%s---",__func__);
    
    [self.view endEditing:YES];//取消所有正在编辑的
    
    if (kNetworkNotReachability) { // 没有网
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share] showWithMessLC:@"网络不给力"];
        return;
    }else{
        
        NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
        NSString *iptype = [userDefaul objectForKey:@"iptype"]; //terminal
        NSString *banben = [userDefaul objectForKey:@"banben"]; //OSVersion
        aLcProducct.shopuser = [AppData share].username;
        
        //设置相对应的提示
        if (aLcProducct.barcode.length == 0) {
            [self showAlertMessage:@"请输入商品编号"];
        }else if(aLcProducct.categoryname.length == 0){
            [self showAlertMessage:@"请选择商品分类"];
        }else if(aLcProducct.productname.length == 0){
            [self showAlertMessage:@"请输入商品名称"];
        }else if (self.photos.count == 0) {
            [self showAlertMessage:@"请为商品添加配图"];
        }else if(aLcProducct.property.length == 0){
            [self showAlertMessage:@"请输入规格命名"];
        }else{
            if (self.productSpecArrs.count > 0){
                for (int i = 0; i < self.productSpecArrs.count; i++) {
                    BOOL isSpecReturn;
                    if ([self.productSpecArrs[i] isKindOfClass:[NSString class]]) {
                        [self showAlertMessage1:@"商品规格信息不能为空"];
                        isSpecReturn = YES;
                    }else{
                        LCProductSpec *aSpec = self.productSpecArrs[i];
                        BOOL isReturn = NO;
                        if (aSpec.specname.length == 0) {
                            [self showAlertMessage1:@"商品规格信息不能为空"];
                            isReturn = YES;
                        }else if ([aSpec.saleprice floatValue] <= 0){
                            [self showAlertMessage1:@"商品销售价不能为0或空"];
                            isReturn = YES;
                        }else if ([aSpec.costprice floatValue] < 0){
                            [self showAlertMessage1:@"商品规格信息不能为空"];
                            isReturn = YES;
                        }else if ([aSpec.numstock floatValue] <= 0){
                            [self showAlertMessage1:@"商品库存不能为0或空"];
                            isReturn = YES;
                        }
                        if (isReturn) {
                            isSpecReturn = YES;
                        }else{
                            isSpecReturn = NO;
                        }
                    }
                    if (isSpecReturn) {
                        return;
                    }
                }
            }
            
            if (self.productPropArrs.count > 0){ //属性不是必须的，但是，如果用户点击添加了就要判断
                for (int j = 0; j < self.productPropArrs.count; j++) {
                    BOOL isPropReturn;
                    if ([self.productPropArrs[j] isKindOfClass:[NSString class]]) {
                        [self showAlertMessage1:@"商品属性信息不能为空"];
                        isPropReturn = YES;
                    }else{
                        LCProductProp *aProp = self.productPropArrs[j];
                        BOOL isReturn = NO;
                        if (aProp.propertyname.length == 0) {
                            [self showAlertMessage1:@"商品属性信息不能为空"];
                            isReturn = YES;
                        }else if (aProp.propertyvalue.length == 0){
                            [self showAlertMessage1:@"商品属性信息不能为空"];
                            isReturn = YES;
                        }
                        if (isReturn) {
                            isPropReturn = YES;
                        }else{
                            isPropReturn = NO;
                        }
                    }
                    if (isPropReturn) {
                        return;
                    }
                }
            }
            //一下设置对应的默认值
            if (![aLcProducct.supportexpress isEqualToString:@"1"]) { //是否支持快递配送
                aLcProducct.supportexpress = @"0";
            }
            if (![aLcProducct.ishot isEqualToString:@"1"]) {
                aLcProducct.ishot = @"0";
            }
            if (![aLcProducct.ispublic isEqualToString:@"1"]) {
                aLcProducct.ispublic = @"0";
            }
            if (aLcProducct.sdescription.length == 0) {
                aLcProducct.sdescription = @"";
            }
            if (aLcProducct.folder.length == 0) {
                aLcProducct.folder = @"";
            }
            if (aLcProducct.mainimage.length == 0) {
                aLcProducct.mainimage = @"";
            }
            [MBProgressHUD showLCHud:self.view];

            //上传图片start
            if (self.photos.count > 0){
                
                if (self.photos.count > 0) {
                    for (int i = 0; i<self.photos.count; i++) {
                        if ([self.photos[i] isKindOfClass:[UIImage class]]) {
                            _localImgCount++;
                        }
                    }
                }
                NSLog(@"p605p---%s-333333--%ld",__func__,(long)_localImgCount);
                if (_localImgCount == 0) { //只有网络图片
                    [self sendDataOnlyWebImg];
                }else{
                    //for循环start
                    for (int i = 0; i < self.photos.count; i++) {
                        if ([self.photos[i] isKindOfClass:[UIImage class]]) {
                            NSData *imgData = UIImageJPEGRepresentation(self.photos[i], 0.8);
                            NSString *imgbase64Str = [imgData base64Encoding];
                            NSString *str64 = [self encodeURL:imgbase64Str];
                            NSString *imgTex = @"jpg";
                            
                            // 1.创建一个网络路径                            
                            NSURL *url = [NSURL URLWithString:ProductAddImgUrl];
                            // 2.创建一个网络请求，分别设置请求方法、请求参数
                            NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
                            requst.HTTPMethod = @"POST";
                            //                        [requst setTimeoutInterval:90];
                            NSString *args = [NSString stringWithFormat:@"data=%@&ext=%@&terminal=%@&osversion=%@&folder=%@",str64,imgTex,iptype,banben,aLcProducct.folder];
                            requst.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];
                            
                            // 3.获得会话对象
                            NSURLSession *session = [NSURLSession sharedSession];
                            
                            //                        NSURLSessionDataTask *sessionDataTask = [session dataTaskWithHTTPGetRequest:requst completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                            //                            if (data != nil) {
                            //                                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
                            //                                NSLog(@"上传图片--%@-\n---errorerrorerror-%@",dict,error);
                            //                                // 发送通知
                            //                                // object 是第几张图片
                            //                                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFIC_NAME object:dict];
                            //                            }
                            //                        }];
                            
                            __weak typeof(self) weakSelf = self;
                            // 4.根据会话对象，创建一个Task任务
                            NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                if (error) {
                                    [MBProgressHUD hideLCHud:self.view];
                                    
                                    if ([actiontype isEqualToString:@"0"]) {
                                        [[MessShowView share]showWithMessLC:@"商品添加失败" login:NO];
                                    }else if ([actiontype isEqualToString:@"1"]) {
                                        [[MessShowView share]showWithMessLC:@"商品加入仓库失败" login:NO];
                                    }else{
                                        [[MessShowView share]showWithMessLC:@"商品编辑保存失败" login:NO];
                                    }
                                    
                                    _isFailed = YES;
                                    weakSelf.finalImgs = [NSMutableArray array];
                                    weakSelf.sendedPhotos = [NSMutableArray array];
                                    return;
                                }else{
                                    if (data != nil) {
                                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
                                        //                                        NSLog(@"上传图片--%@-\n---errorerrorerror-%@",dict,error);
                                        
                                        // 发送通知
                                        // object 是第几张图片
                                        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFIC_NAME object:dict];
                                        //                                        NSLog(@"%s----%@",__func__,[NSThread currentThread]);
                                    }
                                }
                                
                            }];
                            //5.最后一步，执行任务,(resume也是继续执行)。
                            [sessionDataTask resume];
                            
                            
                        }
                    }
                    
                }
                //上传图片end
                
            }
            
            
            
        }
        
    }
    
    
}

-(void)overedSendImg:(NSNotification *)sender
{
    //此处只判断本地图片个数
    NSInteger localImgCount = 0;
    if (self.photos.count > 0) {
        for (int i = 0; i<self.photos.count; i++) {
            if ([self.photos[i] isKindOfClass:[UIImage class]]) { //本地
                localImgCount++;
            }
        }
    }
    // sender.object 接受到的是,每上传一次本地图片调用该方法一次
    NSDictionary *dict = sender.object;

    NSLog(@"pp0923---%s----%@",__func__,dict);
    
    NSString *result = [dict objectForKey:@"m"];
    if ([result isEqualToString:@"success"]) {
        NSString *imgUrl = [dict objectForKey:@"filename"];
        [self.finalImgs addObject:imgUrl];
    }
    
    //当本地图片个数一致时才开始真正上传商品
    if (self.finalImgs.count == localImgCount && localImgCount > 0) {
        
        __weak typeof(self) weakSelf = self;
        
        if (self.photos.count > 0) {
            for (int i = 0; i<self.photos.count; i++) {
                if ([self.photos[i] isKindOfClass:[UIImage class]]) {
                }else{
                    //第一步加入网络图片：最终合并网络图片（self.photos[i]）和本地图片（self.finalImgs
                    NSString *webImgUrl = self.photos[i];
                    [self.sendedPhotos addObject:webImgUrl];
                }
            }
        }
        
        //第二步加入本地上传图片：最终合并网络图片（self.photos[i]）和本地图片（self.finalImgs）
        [self.sendedPhotos addObjectsFromArray:self.finalImgs];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf sendData];
        });
        
    }
    
    
    
}
-(void)sendDataOnlyWebImg
{
    if (self.photos.count > 0) {
        for (int i = 0; i<self.photos.count; i++) {
            if ([self.photos[i] isKindOfClass:[UIImage class]]) {
            }else{
                LCLog(@"%s------%@",__func__,self.photos);
                [self.sendedPhotos addObject:self.photos[i]];
            }
        }
    }
    
    [self sendData];
}
-(void)sendData
{
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"]; //terminal
    NSString *banben = [userDefaul objectForKey:@"banben"]; //OSVersion
    NSString *cid = [userDefaul objectForKey:@"cid"]; //identity
    aLcProducct.shopuser = [AppData share].username;
    // 更新 UI
    //111begin //图片上传成功后才上传商品信息
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setValue:aLcProducct.actiontype forKey:@"actiontype"];
    [dict setValue:aLcProducct.barcode forKey:@"barcode"];
    [dict setValue:aLcProducct.productname forKey:@"productname"];
    [dict setValue:aLcProducct.productid forKey:@"productid"];
    [dict setValue:self.sendedPhotos forKey:@"imagelist"];
    [dict setValue:aLcProducct.categoryid forKey:@"categoryid"];
    [dict setValue:aLcProducct.property forKey:@"property"];
    [dict setValue:aLcProducct.sort forKey:@"sort"];
    [dict setValue:aLcProducct.ishot forKey:@"ishot"];
    [dict setValue:aLcProducct.supportexpress forKey:@"supportexpress"];
    [dict setValue:aLcProducct.sdescription forKey:@"sdescription"];
//    [dict setValue:@"" forKey:@"desc"];
    [dict setValue:aLcProducct.shopuser forKey:@"shopuser"];
    if (self.sendedPhotos.count > 0) {
        aLcProducct.mainimage = self.sendedPhotos[0];
    }else{
        aLcProducct.mainimage = @"";
    }
    [dict setObject:aLcProducct.mainimage forKey:@"mainimage"];
    [dict setObject:aLcProducct.folder forKey:@"folder"];
    
    if (self.addVCStyle == LCProductStyleEdit) {
        [dict setObject:aLcProducct.ispublic forKey:@"ispublic"];
    }
    NSMutableArray *specArrs = [NSMutableArray array];
    NSMutableArray *propArrs = [NSMutableArray array];
    if (self.productSpecArrs.count > 0) {
        for (int i = 0; i<self.productSpecArrs.count; i++) {
            if ([self.productSpecArrs[i] isKindOfClass:[NSString class]]) {
                //防止必填项为空时，判断漏洞导致崩溃
            }else{
                LCProductSpec *aSpec = self.productSpecArrs[i];
                if ([aSpec.mainimage hasPrefix:@"LCPP"]) { //如果前缀是“LCPP”就处理下
                    if (aSpec.mainimage.length > 4) {
                        NSString *itemStr = [aSpec.mainimage substringFromIndex:4];
                        NSInteger item = [itemStr integerValue];
                        if (self.finalImgs.count > item) {
                            aSpec.mainimage = self.finalImgs[item];
                            [self.productSpecArrs replaceObjectAtIndex:i withObject:aSpec];//记得替换下
                        }
                    }else{
                        aSpec.mainimage = @"";
                    }
                }
            }
           
        }
        specArrs = [LCProductSpec mj_keyValuesArrayWithObjectArray:self.productSpecArrs];
    }
    if (self.productPropArrs.count > 0) {
        NSMutableArray *propModelArrs = [NSMutableArray array];
        for (int i = 0; i<self.productPropArrs.count; i++) {
            if ([self.productPropArrs[i] isKindOfClass:[NSString class]]) {
                //防止必填项为空时，判断漏洞导致崩溃
            }else{
                LCProductProp *aProp = self.productPropArrs[i];
                [propModelArrs addObject:aProp];
            }
        }
        propArrs = [LCProductProp mj_keyValuesArrayWithObjectArray:propModelArrs];
    }
    [dict setValue:specArrs forKey:@"productspec"];
    [dict setValue:propArrs forKey:@"productprop"];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        //NSData转换为String
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
        jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
    }
    else if ([jsonData length] == 0 &&
             error == nil){
    }
    else if (error != nil){
    }
    
    if (kNetworkNotReachability) {
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share] showWithMessLC:@"网络不给力,请检查网络"];
        return;
    }

    NSString *dataUrl;
    if (self.addVCStyle == LCProductStyleAdd) {
        dataUrl = [NSString stringWithFormat:ProductAddUrl,cid,iptype,banben,[Utils md5SignStr],[AppData share].username,[AppData share].username];
    }else if (self.addVCStyle == LCProductStyleEdit){
        dataUrl = [NSString stringWithFormat:ProductEditSaveUrl,cid,iptype,banben,[Utils md5SignStr],[AppData share].username,[AppData share].username];
    }
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSURLResponse *theResponse;
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:dataUrl]];
    
    
    NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
    NSLog(@"上传参数----%@",bodyString);
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
    NSString *str = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSString *jjString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"返回结果----%@\n---%@",str,jjString);
    
    if ([jjString rangeOfString:@"success"].location !=NSNotFound) {
        [MBProgressHUD hideLCHud:self.view];
        
        if ([aLcProducct.actiontype isEqualToString:@"0"]) {
            UIAlertView *proAddYesAlert = [[UIAlertView alloc]initWithTitle:@"商品添加成功，是否继续添加？" message:nil delegate:self cancelButtonTitle:@"不添加了" otherButtonTitles:@"继续添加", nil];
            proAddYesAlert.tag = 7781;
            [proAddYesAlert show];
        }else if ([aLcProducct.actiontype isEqualToString:@"1"]) {
            UIAlertView *proFangRuYesAlert = [[UIAlertView alloc]initWithTitle:@"商品加入仓库成功，是否继续添加？" message:nil delegate:self cancelButtonTitle:@"不添加了" otherButtonTitles:@"继续添加", nil];
            proFangRuYesAlert.tag = 7782;
            [proFangRuYesAlert show];

        }else{
            [UIView animateWithDuration:0.4 animations:^{
                //保存成功
                if (self.saveSuccessBlock) {
                    self.saveSuccessBlock(YES);
                }
                [[MessShowView share]showWithMessLC:@"商品编辑保存成功" login:YES];
            } completion:^(BOOL finished) {
                [self.navigationController popViewControllerAnimated:YES];

            }];
           
        }
        
    }else{
        [MBProgressHUD hideLCHud:self.view];
        if ([aLcProducct.actiontype isEqualToString:@"0"]) {
            [[MessShowView share]showWithMessLC:@"商品添加失败" login:NO];
        }else if ([aLcProducct.actiontype isEqualToString:@"1"]) {
            [[MessShowView share]showWithMessLC:@"商品放入仓库失败" login:NO];
        }else{
            if (self.saveSuccessBlock) {
                self.saveSuccessBlock(NO);
            }
            [[MessShowView share]showWithMessLC:@"商品编辑保存失败" login:NO];

        }
        _isFailed = YES;
        self.finalImgs = [NSMutableArray array];
        self.sendedPhotos = [NSMutableArray array];
        return;
        
    }
    
    //111end
    
    
}
#pragma mark ---- 设置头部或者尾部视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 4 && self.productPropArrs.count >= 2) {
        UIView *lcView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
        lcView.backgroundColor = SetColorRGBValue(0xF9F9F9, 1.0);
        return lcView;
    }
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{

    __weak typeof(self) weakSelf = self;
    if (section == 2) {
        AddProductFooterView *footerV = [[AddProductFooterView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        [footerV setupAddProductFooterViewData:@"添加商品规格" isEmptyArr:nil];
        [footerV setFooterViewAddBlock:^{
            [weakSelf.view endEditing:YES];
            [weakSelf.productSpecArrs addObject:KSpecArrPlaceholder];
            [weakSelf.tableView reloadData];
        }];
        return footerV;
    }else if (section == 3){
        //属性最多两个
        if (_productPropArrs.count < 2) {
            AddProductFooterView *footerV;
            if (_productPropArrs.count == 0) {
                footerV = [[AddProductFooterView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 34)];
            }else{
                footerV = [[AddProductFooterView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
            }
            [footerV setupAddProductFooterViewData:@"添加商品属性" isEmptyArr:(_productPropArrs.count == 0)];
            [footerV setFooterViewAddBlock:^{
                [weakSelf.view endEditing:YES];
                [weakSelf.productPropArrs addObject:KPropArrPlaceholder];
                [weakSelf.tableView reloadData];
            }];
            return footerV;
        }
        
    }
    if (section == 0 || section == 4 || section == 6){
        UIView *lcView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
        lcView.backgroundColor = SetColorRGBValue(0xF9F9F9, 1.0);
        return lcView;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section == 6) {
        return 10;
    }else if (section == 4 && self.productPropArrs.count >=2){
        return 10;
    }
    return 0.0000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 50;
    }else if (section == 3){
        if (_productPropArrs.count == 0) {
            return 34;
        }else if (_productPropArrs.count < 2){
            return 50;
        }
    }else if (section == 0 || section == 4 || section == 6){
        return 10;
    }
    return 0.0000001;
}
#pragma mark --- 获取网络该条码对应的商品数据
-(void)getNetData:(NSString *)proBarCodeStr
{
    [MBProgressHUD showLCHud:self.view];
    NSString *barCodeUrl = [NSString stringWithFormat:ProductBarCodeUrl,proBarCodeStr];
    if (kNetworkNotReachability) { // 没有网
        [MBProgressHUD hideLCHud:self.view];
        [[MessShowView share] showWithMessLC:@"网络不给力,请检查网络"];
        return;
    }else{
        
        [NTNetUtil sendRequestWithUrl:barCodeUrl requestName:@"scanBarCodeUrl" method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *resultDict = (NSDictionary *)networkRequest.responseData;
            LCLog(@"111扫码成功获得条码 -zidian--%@\n-%@---\n%@",resultDict,barCodeUrl,aLcProducct);
            if (error) {
                [MBProgressHUD hideLCHud:self.view];
                [[MessShowView share]showWithMessLC:@"没有该商品信息" login:NO];
                //处理扫码没有结果的情况，但是条码框任然显示扫码的结果
                aLcProducct = [AddProduct new];
                aLcProducct.barcode = proBarCodeStr;
                self.photos = [NSMutableArray array];
                self.finalImgs = [NSMutableArray array];
                self.sendedPhotos = [NSMutableArray array];
                [self.productSpecArrs removeAllObjects];
                [self.productSpecArrs addObject:KSpecArrPlaceholder];
                [self.productPropArrs removeAllObjects];
                _isReload = YES;
                [self.tableView reloadData];
                [UIView animateWithDuration:0.1 animations:^{
                    [self.tableView setContentOffset:CGPointMake(0, 0)];
                } completion:^(BOOL finished) {
                    
                }];
                
                return ;
                
            }else{
                NSDictionary *dic = (NSDictionary *)networkRequest.responseData;
                aLcProducct = [AddProduct mj_objectWithKeyValues:dic];
                if ([aLcProducct.m isEqualToString:@"success"]) {
                    
                    [MBProgressHUD hideLCHud:self.view];
                    
                    //扫码成功，先清除原有多规格多属性的数组，如果多规格数组为0，要默认添加一个KSpecArrPlaceholder
                    [self.productSpecArrs removeAllObjects];
                    [self.productPropArrs removeAllObjects];
                    if (aLcProducct.productspec.count > 0) {
                        [self.productSpecArrs addObjectsFromArray:aLcProducct.productspec];
                    }
                    if (self.productSpecArrs.count == 0) {
                        [self.productSpecArrs addObject:KSpecArrPlaceholder];
                    }
                    
                    if (aLcProducct.productprop.count > 0) {
                        [self.productPropArrs addObjectsFromArray:aLcProducct.productprop];
                    }
                    
                    if (aLcProducct.imagelist.count > 0) { //先判断是否有网络请求图片
                        [self.photos addObjectsFromArray:aLcProducct.imagelist];
                    }
                    
                    [self.tableView reloadData];
                }else{
                    
                    [MBProgressHUD hideLCHud:self.view];
                    [[MessShowView share]showWithMessLC:aLcProducct.m login:NO];
                    //处理扫码没有结果的情况，但是条码框任然显示扫码的结果
                    aLcProducct = [AddProduct new];
                    aLcProducct.barcode = proBarCodeStr;
                    self.photos = [NSMutableArray array];
                    self.finalImgs = [NSMutableArray array];
                    self.sendedPhotos = [NSMutableArray array];
                    [self.productSpecArrs removeAllObjects];
                    [self.productSpecArrs addObject:KSpecArrPlaceholder];
                    [self.productPropArrs removeAllObjects];
                    _isReload = YES;
                    [self.tableView reloadData];
                    [UIView animateWithDuration:0.1 animations:^{
                        [self.tableView setContentOffset:CGPointMake(0, 0)];
                    } completion:^(BOOL finished) {
                        
                    }];
                    
                }
                
            }
            
        }];
        
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
}
#pragma mark ---【各种代理方法】
#pragma mark --- 扫码图像点击去扫码
-(void)codeBtClicked
{
    if ([self isCammer]) {
        ZBarScanVC *zbar = [[ZBarScanVC alloc] init];
        
        zbar.delegate = self;
        [self.navigationController pushViewController:zbar animated:YES];
    }else{
        [self noCameraReminder];
        return;
    }
}

#pragma mark -- 多规格删除代理---ProductSpecDeleteCellDelegate
-(void)specDeleteBtClicked:(UIButton *)deleteBt
{
    NSInteger currentRow = deleteBt.tag-1500;
    LCLog(@"多规格删除代理---%ld",currentRow);
    if (self.productSpecArrs.count > currentRow) {
        [self.productSpecArrs removeObjectAtIndex:currentRow];
        [self.tableView reloadData];
    }
}

#pragma mark -- 多属性删除代理---ProductPropDeleteCellDelegate
-(void)propDeleteBtClicked:(UIButton *)deleteBt
{
    NSInteger currentRow = deleteBt.tag-1600;
    LCLog(@"多shuxign删除代理---%ld",currentRow);
    if (self.productPropArrs.count > currentRow) {
        [self.productPropArrs removeObjectAtIndex:currentRow];
        [self.tableView reloadData];
    }
}

#pragma mark --- tableView 数据源代理
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    
    if (indexPath.section == 0) {
        //商品编码板块
        if (indexPath.row == 0) {
            
            ProductCodeCell *cell = [ProductCodeCell cellWithTableView:tableView];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.proCodeTf.delegate = self;
            cell.proCodeTf.tag = 6600;
            cell.proCodeTf.keyboardType = UIKeyboardTypeNumberPad;
            cell.proCodeTf.autocorrectionType = UITextAutocorrectionTypeNo;
            
            if (aLcProducct.barcode.length > 0) {
                cell.proCodeTf.text = aLcProducct.barcode;
            }
            //刷新界面（不仅需要_isReload == YES，还要判断aLcProducct.barcode.length）
            if (_isReload == YES && aLcProducct.barcode.length == 0) {
                cell.proCodeTf.text = nil;
            }
            //手动输入条码
            cell.proCodeTfClickedBlock = ^(ProductCodeCell *aProductCodeCell){
                if (aProductCodeCell.proCodeTf.text.length >= 13) {
                    [aProductCodeCell.proCodeTf resignFirstResponder];
                    //添加商品时，手动输入才可以去发送请求
                    if (self.addVCStyle == LCProductStyleAdd) {
                        _isReload = YES;
                        aLcProducct = [AddProduct new];
                        aLcProducct.barcode = [aProductCodeCell.proCodeTf.text substringWithRange:NSMakeRange(0, 13)];
                        weakSelf.photos = [NSMutableArray array];
                        weakSelf.finalImgs = [NSMutableArray array];
                        weakSelf.sendedPhotos = [NSMutableArray array];
                        //此处同扫码成功一样，在getNetData里面处理多规格多属性数组
                        [weakSelf.tableView reloadData];
                        aProductCodeCell.proCodeTf.text = aLcProducct.barcode;
                        [weakSelf getNetData:aLcProducct.barcode];
                    }else{
                        aLcProducct.barcode = [aProductCodeCell.proCodeTf.text substringWithRange:NSMakeRange(0, 13)];
                        [[MessShowView share]showWithMess:@"商品编码是13位数字哦~"];
                    }
                    
                    NSLog(@"手动输入条码--%@\n---%@",aProductCodeCell.proCodeTf.text,aLcProducct.barcode);
                }else{
                    aLcProducct.barcode = aProductCodeCell.proCodeTf.text;
                }
                
            };
            return cell;
            
        }else if (indexPath.row == 1){
            ProductArrowCell *cell = [ProductArrowCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setupProductArrowCell:@"商品分类" aLCProduct:aLcProducct andRow:indexPath.row];
            if (aLcProducct.categoryname.length > 0) {
                cell.categoryTf.text = aLcProducct.categoryname;
            }
            if (_isReload && aLcProducct.categoryname.length == 0) {
                cell.categoryTf.text= nil;
            }
            cell.arrowBtClickedBlock = ^(ProductArrowCell *aProArrowCell){
                [weakSelf.view endEditing:YES];
                classifyViewController *categoryVC = [[classifyViewController alloc]init];
                categoryVC.delegate = weakSelf;
                [self.navigationController pushViewController:categoryVC animated:YES];
            };
            return  cell;

        }else if (indexPath.row == 2){ //商品名称
            ProductTextCell *cell = [ProductTextCell cellWithTableView:tableView];
            cell.detailTf.text = @"";
            cell.detailTf.tag = 6602;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setupProductTextCell:@"商品名称" placeholderStr:@"请输入商品名称" aLCProduct:aLcProducct andRow:indexPath.row];
            cell.detailTf.delegate = self;
            cell.detailTf.tag = 6057;
            //先判断有没有扫码结果
            if (aLcProducct.productname.length > 0) {
                cell.detailTf.text = aLcProducct.productname;
            }
            if (_isReload && aLcProducct.productname.length == 0) {
                cell.detailTf.text= nil;
            }
            cell.detailTfBlock = ^(ProductTextCell *aProductTextCell){
                aLcProducct.productname = aProductTextCell.detailTf.text;
            };
            return cell;
        }else if (indexPath.row == 3){
            ProductTextCell *cell = [ProductTextCell cellWithTableView:tableView];
            cell.detailTf.text = @"";
            cell.detailTf.tag = 6603;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setupProductTextCell:@"商品排序" placeholderStr:@"数字越大越靠前" aLCProduct:aLcProducct andRow:indexPath.row];
            cell.detailTf.delegate = self;
            cell.detailTf.keyboardType = UIKeyboardTypeNumberPad;
            //先判断有没有扫码结果
            if (aLcProducct.sort.length > 0 && [aLcProducct.sort floatValue] >= 0) {
                cell.detailTf.text = aLcProducct.sort;
            }else{
                cell.detailTf.text =  @"0";
            }
            if (_isReload && aLcProducct.sort.length == 0) {
                cell.detailTf.text= @"0";
            }
            cell.detailTfBlock = ^(ProductTextCell *aProductTextCell){
                aLcProducct.sort = aProductTextCell.detailTf.text;
            };
            return cell;

        }else if (indexPath.row == 4){
            ProduntImageCell *cell = [ProduntImageCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            if (self.photos.count > 0 ) {
                
                [cell setupProduntImageCell:self.photos aLCProduct:aLcProducct];
            }
            
            if (_isReload && self.photos.count == 0 ) {
                
                [cell setupProduntImageCell:nil aLCProduct:aLcProducct];
            }
            
            //商品图片点击处理
            cell.proimgbtClickedBlock = ^(ProduntImageCell *aProImageCell){
                //先隐藏键盘
                [weakSelf.view endEditing:YES];
                UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
                [sheet showInView:self.view];
                
            };
            //删除按钮点击处理
            __weak typeof(cell) weakCell = cell;
            cell.deletebtClickedBlock = ^(ProduntImageCell *aProImageCell,NSInteger btTag){
                NSInteger deleteIndex = -10;
                if (btTag == 600) {
                    deleteIndex = 0;
                }else if (btTag == 601){
                    deleteIndex = 1;
                }else if (btTag == 602){
                    deleteIndex = 2;
                }
                //执行for循环在removeObjectAtIndex之前
                if (self.productSpecArrs.count > 0) {
                    for (int j = 0; j<self.productSpecArrs.count; j++) {
                        if ([self.productSpecArrs[j] isKindOfClass:[NSString class]]) {
                            //此时没有处理多规格
                        }else{
                            //图片数组删除，如果cell上有图片并且与所删除的一致时，也要清除
                            LCProductSpec *aSpec = self.productSpecArrs[j];
                            if (self.photos.count > deleteIndex) {
                                if ([self.photos[deleteIndex] isKindOfClass:[UIImage class]]) {
                                    if (aSpec.localImg == self.photos[deleteIndex]) {
                                        aSpec.mainimage = nil;
                                        aSpec.localImg = nil;
                                    }
                                }else{
                                    if ([aSpec.mainimage isEqualToString:self.photos[deleteIndex]]) {
                                        aSpec.mainimage = nil;
                                        aSpec.localImg = nil;
                                    }
                                }
                            }
                            
                        }
                    }
                }
                
                [weakSelf.photos removeObjectAtIndex:deleteIndex];
                
                [weakSelf.tableView reloadData];
                //删除按钮点击后刷新
                [weakCell setupProduntImageCell:weakSelf.photos aLCProduct:aLcProducct];
            };
            
            return cell;
        }
        
        
    }else if (indexPath.section == 1){
        ProductTextCell *cell = [ProductTextCell cellWithTableView:tableView];
        cell.detailTf.text = @"";
        cell.detailTf.tag = 6605;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setupProductTextCell:@"规格命名" placeholderStr:@"用于多规格显示名称，例如：口味、尺码等" aLCProduct:aLcProducct andRow:indexPath.row];
        cell.detailTf.delegate = self;
        cell.detailTf.tag = 6058;
        //先判断有没有扫码结果
        if (aLcProducct.property.length > 0) {
            cell.detailTf.text = aLcProducct.property;
        }
        if (_isReload && aLcProducct.property.length == 0) {
            cell.detailTf.text= nil;
        }
        cell.detailTfBlock = ^(ProductTextCell *aProductTextCell){
            aLcProducct.property = aProductTextCell.detailTf.text;
        };
        return cell;
        
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) { //默认至少一个规格
            ProductSpecCell *cell = [ProductSpecCell cellWithTableView:tableView];
            
            //跳到选择图片界面
            cell.ProductSpecCellArrowBlock = ^(){
                [weakSelf.view endEditing:YES];
                SelectImageViewController *selectImgVC = [[SelectImageViewController alloc]init];
                selectImgVC.imgUrlArrs = self.photos;
                
                [selectImgVC setSelectImageVCBlock:^(BOOL isWeb, NSString *webImgUrl, NSInteger localItem,UIImage *currentImg,NSInteger indexItem) {
                    LCProductSpec *aSpec;
                    if ([weakSelf.productSpecArrs[indexPath.row] isKindOfClass:[NSString class]]) {
                        aSpec = [[LCProductSpec alloc]init]; //处理先直接点击（规格的其它都没有输入）图片箭头
                        [weakSelf.productSpecArrs replaceObjectAtIndex:indexPath.row withObject:aSpec];
                    }else{
                        aSpec = self.productSpecArrs[indexPath.row];
                    }
                    if (isWeb) {
                        aSpec.mainimage = webImgUrl;
                        aSpec.localImg = nil;
                    }else{
                        aSpec.mainimage = [NSString stringWithFormat:@"LCPP%ld",(long)localItem];
                        aSpec.localImg = currentImg;
                    }
                    [weakSelf.tableView reloadData];
                }];
                
                [weakSelf.navigationController pushViewController:selectImgVC animated:YES];
            };
            
            LCProductSpec *aSpec;
            if (self.productSpecArrs.count > 0) {
                if ([self.productSpecArrs[0] isKindOfClass:[NSString class]]) {
                    aSpec = nil;
                }else{
                    aSpec = self.productSpecArrs[0];
                }
                [cell setupProductSpecCell:aSpec];
                
                [cell setSpecBlock:^(LCProductSpec *aSpec) {
                    if (weakSelf.productSpecArrs.count > 0) {
                        [weakSelf.productSpecArrs replaceObjectAtIndex:0 withObject:aSpec];
                    }
                }];
            }
            
            return cell;
        }else{
            ProductSpecDeleteCell *cell = [ProductSpecDeleteCell cellWithTableView:tableView];
            cell.delegate = self;
            cell.ProductSpecDeleteCellArrowBlock = ^(){
                [weakSelf.view endEditing:YES];
                SelectImageViewController *selectImgVC = [[SelectImageViewController alloc]init];
                selectImgVC.imgUrlArrs = self.photos;
                [selectImgVC setSelectImageVCBlock:^(BOOL isWeb, NSString *webImgUrl, NSInteger localItem,UIImage *currentImg,NSInteger indexItem) {
                    LCProductSpec *aSpec;
                    if ([weakSelf.productSpecArrs[indexPath.row] isKindOfClass:[NSString class]]) {
                        aSpec = [[LCProductSpec alloc]init]; //处理先直接点击（规格的其它都没有输入）图片箭头
                        [weakSelf.productSpecArrs replaceObjectAtIndex:indexPath.row withObject:aSpec];
                    }else{
                        aSpec = self.productSpecArrs[indexPath.row];
                    }
                    if (isWeb) {
                        aSpec.mainimage = webImgUrl;
                        aSpec.localImg = nil;
                    }else{
                        aSpec.mainimage = [NSString stringWithFormat:@"LCPP%ld",(long)localItem];
                        aSpec.localImg = currentImg;
                    }
                    [weakSelf.tableView reloadData];
                }];
                [weakSelf.navigationController pushViewController:selectImgVC animated:YES];
            };
            //cell填充数据
            if (self.productSpecArrs.count > indexPath.row) {
                LCProductSpec *aSpec;
                if ([self.productSpecArrs[indexPath.row] isKindOfClass:[NSString class]]) {
                    aSpec = nil;
                }else{
                    aSpec = self.productSpecArrs[indexPath.row];
                }
                [cell setupProductSpecDeleteCell:aSpec deleteBtTag:indexPath.row];
                
                [cell setSpecDeleteBlock:^(LCProductSpec *aSpec, NSInteger currentRow) {
                    if (weakSelf.productSpecArrs.count > currentRow) {
                        [weakSelf.productSpecArrs replaceObjectAtIndex:currentRow withObject:aSpec];
                        LCLog(@"setSpecDeleteBlock-----%@",weakSelf.productSpecArrs);
                    }
                }];
            }
            return cell;
            
        }
        
    }else if (indexPath.section == 3){
        ProductPropDeleteCell *cell = [ProductPropDeleteCell cellWithTableView:tableView];
        cell.delegate = self;
        if (self.productPropArrs.count > indexPath.row) {
            LCProductProp *aProp;
            if ([self.productPropArrs[indexPath.row] isKindOfClass:[NSString class]]) {
                aProp = nil;
            }else{
                aProp = self.productPropArrs[indexPath.row];
            }
            [cell setupProductPropDeleteCell:aProp deleteBtTag:indexPath.row];
            
            [cell setPropDeleteBlock:^(LCProductProp *aProp, NSInteger currentRow) {
                if (weakSelf.productPropArrs.count > currentRow) {
                    [weakSelf.productPropArrs replaceObjectAtIndex:currentRow withObject:aProp];
                }
            }];
        }
        
    
        return cell;

        
        
    }else if (indexPath.section == 4){
        ProductSwitchCell *cell = [ProductSwitchCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setupProductSwitchCell:indexPath.row aLCProduct:aLcProducct];
        cell.rightSwitchClickedBlock = ^(BOOL switchStatus){
            if (switchStatus) {
                if (indexPath.row == 0) {
                    aLcProducct.supportexpress = @"1";
                }else if (indexPath.row == 1){
                    aLcProducct.ishot = @"1";
                }else{
                    aLcProducct.ispublic = @"1";
                }
            }else{
                if (indexPath.row == 0) {
                    aLcProducct.supportexpress = @"0";
                }else if (indexPath.row == 1){
                    aLcProducct.ishot = @"0";
                }else{
                    aLcProducct.ispublic = @"0";
                }
            }
        };
        return cell;
    }else if (indexPath.section == 5){
        ProductArrowCell *cell = [ProductArrowCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setupProductArrowCell:@"商品简介" aLCProduct:aLcProducct andRow:indexPath.row];
        if (aLcProducct.sdescription.length > 0) {
            cell.detaileLb.text = @"已添加";
            cell.detaileLb.textColor = KAddLeftLbColor;
        }
        cell.arrowBtClickedBlock = ^(ProductArrowCell *aProArrowCell){
            [weakSelf.view endEditing:YES];
            ProductIntroductViewController *proIntroVC = [[ProductIntroductViewController alloc]init];
            __weak typeof(aProArrowCell) weakCell = aProArrowCell;
            proIntroVC.overTextIntroBlock = ^(NSString *textIntro){
                if (textIntro.length > 0) {
                    aLcProducct.sdescription = textIntro;
                    weakCell.detaileLb.text = @"已添加";
                    weakCell.detaileLb.textColor = KAddLeftLbColor;
                }
                
            };
            proIntroVC.lc_textIntroStr = aLcProducct.sdescription;
            [self.navigationController pushViewController:proIntroVC animated:YES];
        };
        return  cell;
    }else if (indexPath.section == 6){
        ProductArrowCell *cell = [ProductArrowCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setupProductArrowCell:@"商品图文描述" aLCProduct:aLcProducct andRow:indexPath.row];
        cell.arrowBtClickedBlock = ^(ProductArrowCell *aProArrowCell){
            [weakSelf.view endEditing:YES];
            ProductImgTextIntroductViewController *proIntroVC = [[ProductImgTextIntroductViewController alloc]init];
            __weak typeof(aProArrowCell) weakCell = aProArrowCell;
            proIntroVC.overImgTextIntroBlock = ^(NSString *imgTextStr){
                weakCell.detaileLb.text = @"已添加";
                weakCell.detaileLb.textColor = KAddLeftLbColor;
            };
            
            [self.navigationController pushViewController:proIntroVC animated:YES];
        };
        return  cell;
    }
    return nil;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    }else if (section == 1){ //规格命名
        return 1;
    }else if (section == 2){ //多规格(至少一个)
        return _productSpecArrs.count;
    }else if (section == 3){ //多属性
        return _productPropArrs.count;
    }else if (section == 4){
        if (self.addVCStyle == LCProductStyleEdit) {
            return 3; //编辑多了个“是否上架上架”
        }
        return 2;
    }else if (section == 5){
        return 1;
    }else if (section == 6){
        return 1;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 4) {
        return 100;
    }else if (indexPath.section == 2){
        if (self.productSpecArrs.count > indexPath.row) {
            if ([self.productSpecArrs[indexPath.row] isKindOfClass:[NSString class]]) {
            }else{
                LCProductSpec *aSpec = self.productSpecArrs[indexPath.row];
                if (aSpec.mainimage.length > 0 || aSpec.localImg) {
                    return 360+10+55;
                }
            }
        }
        return 360+10;
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            return 90;
        }
        return 90+10;
    }else{
        return 45;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //商品图文描述暂时不做，所以为6，否则为7
    return 6;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ---UITextField代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 6600 || textField.tag == 6603) {//6600条码,6603商品排序
        //  判断输入的是否为数字 (只能输入数字)
        NSString *validRegEx =@"^[0-9]*$";
        NSPredicate *regExPredicate =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", validRegEx];
        BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:string];
        if (myStringMatchesRegEx){
            return YES;
        }else{
            return NO;
        }
    }else{
        return YES;
    }
    
}


#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    [picker dismissViewControllerAnimated:NO completion:nil];
    if (assets.count == 1) {
        ALAsset *asset = assets[0];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        //选择照片后就存入照片数组
        [self.photos addObject:tempImg];
        
        CropImgViewController *cropVC = [[CropImgViewController alloc]init];
        cropVC.scropedImg = (UIImage *)[self.photos lastObject];
        __weak typeof(self) weakSelf = self;
        cropVC.overCropedImgBlock = ^(UIImage *cropedImg){
            
            [weakSelf.photos replaceObjectAtIndex:weakSelf.photos.count-1 withObject:cropedImg];
            [weakSelf.tableView reloadData];
            
        };
        [self.navigationController pushViewController:cropVC animated:YES];
        
    }
    //添加图片成功后要刷新界面（应给可以不加下面一句）
    [self.tableView reloadData];
    
}

-(BOOL)isCammer
{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied){
        
        //NSLog(@"相机权限受限");
        return NO;
    }else{
        //NSLog(@"相机可以使用");
        return YES;
    }
}
//#pragma mark --- 判断有没有调用相机的权限
//- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
//    BOOL status = NO;
//    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//    if(authStatus == AVAuthorizationStatusAuthorized) {
//        status = YES;
//    } else if (authStatus == AVAuthorizationStatusDenied) {
//        status = NO;
//    } else if (authStatus == AVAuthorizationStatusRestricted) {
//        status = NO;
//    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
//        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//            if(granted){
//                if (block) {
//                    block(granted);
//                }
//            } else {
//                if (block) {
//                    block(granted);
//                }
//            }
//        }];
//        return;
//    }
//    if (block) {
//        block(status);
//    }
//}
#pragma mark --- 没有调用相机的权限提示
-(void)noCameraReminder
{
    UIAlertView *alert;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                           message:@"如果你想继续使用相机，请在iPhone的“设置”-“隐私”-“相机”中，找到懒猫社长商家版允许"
                                          delegate:nil
                                 cancelButtonTitle:@"确定"
                                 otherButtonTitles:nil, nil];
    } else {
        alert = [[UIAlertView alloc]initWithTitle:@"您没有访问相机权限" message:@"如果你想继续使用相机，请在iPhone的“设置”-“隐私”-“照片”中，找到懒猫社长商家版允许" delegate:self cancelButtonTitle:@"不允许" otherButtonTitles:@"前往", nil];
        alert.tag = 7780;
        [alert show];
        
    }
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case 7780:  //没有调用相机的权限处理
            if (buttonIndex == 1) {
                [[UIApplication sharedApplication] openURL:[NSURL  URLWithString:UIApplicationOpenSettingsURLString]];
            }
            break;
            
        case 7781: //添加商品成功提示是否继续添加
            if (buttonIndex == 0) {
                [self.navigationController popViewControllerAnimated:YES];
            }else if (buttonIndex == 1){
                aLcProducct = [AddProduct new];
                self.photos = [NSMutableArray array];
                self.finalImgs = [NSMutableArray array];
                self.sendedPhotos = [NSMutableArray array];
                [self.productSpecArrs removeAllObjects];
                [self.productSpecArrs addObject:KSpecArrPlaceholder];
                [self.productPropArrs removeAllObjects];
                _isReload = YES;
                [self.tableView reloadData];
                [UIView animateWithDuration:0.1 animations:^{
                    [self.tableView setContentOffset:CGPointMake(0, 0)];
                } completion:^(BOOL finished) {
                    
                }];
            }
            break;
            
        case 7782:
            if (buttonIndex == 0) {
                [self.navigationController popViewControllerAnimated:YES];
            }else if (buttonIndex == 1){
                aLcProducct = [AddProduct new];
                self.photos = [NSMutableArray array];
                self.finalImgs = [NSMutableArray array];
                self.sendedPhotos = [NSMutableArray array];
                [self.productSpecArrs removeAllObjects];
                [self.productSpecArrs addObject:KSpecArrPlaceholder];
                [self.productPropArrs removeAllObjects];
                _isReload = YES;
                
                [self.tableView reloadData];
                [UIView animateWithDuration:0.1 animations:^{
                    [self.tableView setContentOffset:CGPointMake(0, 0)];
                } completion:^(BOOL finished) {
                    
                }];
            }
            break;
            
        default:
            break;
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        if ([self isCammer]) {
            UIImagePickerController *cameraUI = [UIImagePickerController new];
            cameraUI.allowsEditing = NO;
            cameraUI.delegate = self;
            cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
            cameraUI.cameraFlashMode=UIImagePickerControllerCameraFlashModeAuto;
            [self presentViewController: cameraUI animated: YES completion:nil];
            
        }else{
            [self noCameraReminder];
            return;
        }
        
    }else if (buttonIndex == 1){
        //只能选择一张图片
        self.picker = [[AJPhotoPickerViewController alloc] init];
        self.picker.delegate = self;
        self.picker.assetsFilter = [ALAssetsFilter allPhotos];
        self.picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        self.picker.showEmptyGroups = YES;
        //跳转到相册
        [self presentViewController:self.picker animated:YES completion:^{
            
        }];
    }
    
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    if ([self isCammer]) {
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing = NO;
        cameraUI.delegate = self;
        cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode=UIImagePickerControllerCameraFlashModeAuto;
        
        [self presentViewController: cameraUI animated: YES completion:nil];
    }else{
        [self noCameraReminder];
        return;
    }
}
#pragma mark --- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImageWriteToSavedPhotosAlbum(originalImage, nil, nil, nil);
    }
    [self.photos addObject:originalImage];
    
    CropImgViewController *cropVC = [[CropImgViewController alloc]init];
    cropVC.scropedImg = (UIImage *)[self.photos lastObject];
    __weak typeof(self) weakSelf = self;
    cropVC.overCropedImgBlock = ^(UIImage *cropedImg){
        
        [weakSelf.photos replaceObjectAtIndex:weakSelf.photos.count-1 withObject:cropedImg];
        [weakSelf.tableView reloadData];
        
    };
    //先push再dismiss效果更好
    [self.navigationController pushViewController:cropVC animated:NO];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *) picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark --- 选择类型代理
-(void)backPassName:(NSString *)name nameId:(NSString *)nameID
{
    aLcProducct.categoryname = name;
    aLcProducct.categoryid = nameID;
    [self.tableView reloadData];
}
#pragma mark --- 扫码成功代理
- (void)senNum:(NSString *)num
{
    if (self.addVCStyle == LCProductStyleAdd) {
        _isReload = YES; //扫码成功，类似于上传成功后继续上传的逻辑，因为有些时候不停地扫码；
        aLcProducct = [AddProduct new];
        aLcProducct.barcode = num;
        self.photos = [NSMutableArray array];
        self.finalImgs = [NSMutableArray array];
        self.sendedPhotos = [NSMutableArray array];
        //扫码成功后，多规格多属性数组在getNetData中设置
        [self.tableView reloadData];
        [self getNetData:num];
    }else{
        aLcProducct.barcode = num;
        [self.tableView reloadData];
    }
}

#pragma mark --- 图片base64编码
- (NSString*)encodeURL:(NSString *)string
{
    NSString *newString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),kCFStringEncodingUTF8));
    if (newString) {
        return newString;
    }
    return @"";
}
@end

